


<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.8.0">
    <title>使用 axios 访问 API — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="zh" href="using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="使用 axios 访问 API — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org//images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="使用 axios 访问 API — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="../../images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../../images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../../images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../../images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../../images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../../images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../../images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../../images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../../images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="../../images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../../images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../../images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../../images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="../../images/logo.png" type="image/png">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="../../manifest.json">

    <!-- <link href="https://fonts.googleapis.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'> -->
    <!-- <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'> -->

    <link href="https://code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- main page styles -->
    <link rel="stylesheet" href="../../css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="../../js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "cookbook"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>
  </head>
  <body class="docs">
    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="../../index.html"></a>
    </div>
    <div id="header">
  <a id="logo" href="../../index.html">
    <img src="../../images/logo.png" alt="vue logo">
    <span>Vue.js</span>
  </a>
  <ul id="nav">
    <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="../guide/index.html" class="nav-link">教程</a></li>
        <li><a href="../api/index.html" class="nav-link">API</a></li>
        <li><a href="../style-guide/index.html" class="nav-link">风格指南</a></li>
        <li><a href="../examples/index.html" class="nav-link">示例</a></li>
        <li><a href="index.html" class="nav-link current">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li><a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">Vue Mastery (英文)</a></li>
        <li><a href="https://vueschool.io/?friend=vuejs&amp;utm_source=Vuejs.org&amp;utm_medium=Link&amp;utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="noopener">Vue School (英文)</a></li>
        <li><a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">DCloud 视频教程</a></li>
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="../guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="../../resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="../../support-vuejs/index.html" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../support-vuejs/index.html#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="../../support-vuejs/index.html#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&amp;utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html" class="nav-link" target="_blank" rel="noopener">Tiếng Việt</a></li>
  </ul>
</li>

<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>

  </ul>
</div>

    
      <div id="main" class="fix-sidebar">
        
          
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&amp;hmpl=&amp;hmcu=&amp;hmkw=&amp;hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/dcloud.gif" alt="">
    </a>
    </div>
    <div>
    <a href="https://youzan.github.io/vant?source=vuejsorg" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/vant.png" alt="">
    </a>
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->

      
        <h2>
          
          Cookbook<sup class="beta">beta</sup>
          
        </h2>
        <ul class="menu-root">
  
    
    
    <li>
      <a href="index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
    <li>
      <a href="adding-instance-properties.html" class="sidebar-link">添加实例属性</a>
    </li>
  
    
    
    <li>
      <a href="form-validation.html" class="sidebar-link">表单校验</a>
    </li>
  
    
    
    <li>
      <a href="editable-svg-icons.html" class="sidebar-link">可编辑的 SVG 图标系统</a>
    </li>
  
    
    
    <li>
      <a href="serverless-blog.html" class="sidebar-link">创建一个基于 CMS 的博客</a>
    </li>
  
    
    
    <li>
      <a href="unit-testing-vue-components.html" class="sidebar-link">Vue 组件的单元测试</a>
    </li>
  
    
    
    <li>
      <a href="creating-custom-scroll-directives.html" class="sidebar-link">创建自定义滚动指令</a>
    </li>
  
    
    
    <li>
      <a href="debugging-in-vscode.html" class="sidebar-link">在 VS Code 中调试</a>
    </li>
  
    
    
    <li>
      <a href="using-axios-to-consume-apis.html" class="sidebar-link current">使用 axios 访问 API</a>
    </li>
  
    
    
    <li>
      <a href="avoiding-memory-leaks.html" class="sidebar-link">避免内存泄漏</a>
    </li>
  
    
    
    <li>
      <a href="client-side-storage.html" class="sidebar-link">客户端存储</a>
    </li>
  
    
    
    <li>
      <a href="packaging-sfc-for-npm.html" class="sidebar-link">Packaging Vue Components for npm</a>
    </li>
  
    
    
    <li>
      <a href="dockerize-vuejs-app.html" class="sidebar-link">Dockerize Vue.js App</a>
    </li>
  
    
    
    <li>
      <a href="practical-use-of-scoped-slots.html" class="sidebar-link">Practical use of scoped slots with GoogleMaps</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content cookbook with-sidebar ">
  
    
      
<div id="ad">
  <span style="float: right;">广告</span>
  <a href="https://time.geekbang.org/column/intro/216?code=mM%2FdqOPks0VQ7EkYGPNisoEpHDsb0ViHBXYa%2Fyg02k8%3D&amp;utm_term=SPoster" target="_blank" rel="sponsored noopener">
    <img src="../../images/geekbang-ad.jpg">
  </a>
  <!-- <a href="https://ke.qq.com/course/392130?saleToken=992600&from=pclink" target="_blank" rel="sponsored noopener">
    <img src="/images/tencent-ad.png">
  </a> -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CKYIK2QU&placement=vuejsorg"
    id="_carbonads_js">
  </script> -->
</div>


    
  
  
    <h1>使用 axios 访问 API</h1>
  

  <div class="ad-pagetop">
  <a href="http://www.tp-shop.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">TPshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时Vue视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div>


  
    <h2 id="基本的示例"><a href="#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B" class="headerlink" title="基本的示例"></a>基本的示例</h2><p>有很多时候你在构建应用时需要访问一个 API 并展示其数据。做这件事的方法有好几种，而使用基于 promise 的 HTTP 客户端 <a href="https://github.com/axios/axios" target="_blank" rel="noopener">axios</a> 则是其中非常流行的一种。</p>
<p>在本次实践中，我们会使用 <a href="https://www.coindesk.com/api/" target="_blank" rel="noopener">CoinDesk API</a> 来完成展示比特币价格且每分钟更新的工作。首先，我们要通过 npm/Yarn 或一个 CDN 链接安装 axios。</p>
<p>我们有很多种方式可以从 API 请求信息，但是最好首先确认这些数据看起来长什么样，以便进一步确定如何展示它。为此，我们会调用一次这个 API 并输出结果，以便我们能够看清楚它。如 CoinDesk 的 API 文档所述，请求会发送到 <code>https://api.coindesk.com/v1/bpi/currentprice.json</code>。所以，我们首先创建一个 data 里的属性以最终放置信息，然后将会在 <code>mounted</code> 生命周期钩子中获取数据并赋值过去：</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  data () &#123;
    <span class="hljs-keyword">return</span> &#123;
      <span class="hljs-attr">info</span>: <span class="hljs-literal">null</span>
    &#125;
  &#125;,
  mounted () &#123;
    axios
      .get(<span class="hljs-string">'https://api.coindesk.com/v1/bpi/currentprice.json'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> (<span class="hljs-keyword">this</span>.info = response))
  &#125;
&#125;)</code></pre>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  &#123;&#123; info &#125;&#125;
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>我们得到的东西是这样的：</p>
<p></p><p data-height="350" data-theme-id="32763" data-slug-hash="80043dfdb7b90f138f5585ade1a5286f" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="First Step Axios and Vue" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Vue (<a href="https://codepen.io/Vue" target="_blank" rel="noopener">@Vue</a>)的 <a href="https://codepen.io/team/Vue/pen/80043dfdb7b90f138f5585ade1a5286f/" target="_blank" rel="noopener">axios 和 Vue：第一步</a>。</p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<p>很好！我们已经得到了一些数据。但是它看起来还比较乱，所以我们会更好的展示它并添加一些错误处理，以防出现异常情况或请求超时。</p>
<h2 id="真实示例：和数据协同工作"><a href="#%E7%9C%9F%E5%AE%9E%E7%A4%BA%E4%BE%8B%EF%BC%9A%E5%92%8C%E6%95%B0%E6%8D%AE%E5%8D%8F%E5%90%8C%E5%B7%A5%E4%BD%9C" class="headerlink" title="真实示例：和数据协同工作"></a>真实示例：和数据协同工作</h2><h3 id="从一个-API-展示数据"><a href="#%E4%BB%8E%E4%B8%80%E4%B8%AA-API-%E5%B1%95%E7%A4%BA%E6%95%B0%E6%8D%AE" class="headerlink" title="从一个 API 展示数据"></a>从一个 API 展示数据</h3><p>通常情况下，我们需要的信息已经包含在了响应中，只需要遍历我们保存下来的内容就能正确地获取。在这个例子中，我们可以看到我们需要的价格信息在 <code>response.data.bpi</code> 中。如果我们换用这个，则输出是下面这样的：</p>
<pre><code class="hljs js">axios
  .get(<span class="hljs-string">'https://api.coindesk.com/v1/bpi/currentprice.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> (<span class="hljs-keyword">this</span>.info = response.data.bpi))</code></pre>
<p></p><p data-height="200" data-theme-id="32763" data-slug-hash="6100b10f1b4ac2961208643560ba7d11" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Second Step Axios and Vue" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Vue (<a href="https://codepen.io/Vue" target="_blank" rel="noopener">@Vue</a>)的 <a href="https://codepen.io/team/Vue/pen/6100b10f1b4ac2961208643560ba7d11/" target="_blank" rel="noopener">axios 和 Vue：第二步</a>。 </p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<p>这让展示的工作变得容易了很多，所以我们可以更新 HTML 以从获取的数据中仅仅展示真正需要的信息。我们会创建一个<a href="../api/index.html#Vue-filter">过滤器</a>来确保小数部分的合理展示。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bitcoin Price Index<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-for</span>=<span class="hljs-string">"currency in info"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"currency"</span>
  &gt;</span>
    &#123;&#123; currency.description &#125;&#125;:
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lighten"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">v-html</span>=<span class="hljs-string">"currency.symbol"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>&#123;&#123; currency.rate_float | currencydecimal &#125;&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<pre><code class="hljs js">filters: &#123;
  currencydecimal (value) &#123;
    <span class="hljs-keyword">return</span> value.toFixed(<span class="hljs-number">2</span>)
  &#125;
&#125;,</code></pre>
<p></p><p data-height="300" data-theme-id="32763" data-slug-hash="9d59319c09eaccfaf35d9e9f11990f0f" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Third Step Axios and Vue" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Vue (<a href="https://codepen.io/Vue" target="_blank" rel="noopener">@Vue</a>)的 <a href="https://codepen.io/team/Vue/pen/9d59319c09eaccfaf35d9e9f11990f0f/" target="_blank" rel="noopener">axios 和 Vue：第三步</a>。</p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<h3 id="错误处理"><a href="#%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86" class="headerlink" title="错误处理"></a>错误处理</h3><p>很多时候我们可能并没有从 API 获取想要的数据。这可能是由于很多种因素引起的，比如 axios 调用可能由于多种原因而失败，包括但不限于：</p>
<ul>
<li>API 不工作了；</li>
<li>请求发错了；</li>
<li>API 没有按我们预期的格式返回信息。</li>
</ul>
<p>当发送这个请求的时候，我们应该检查一下这些情况，并在所有情况下都返回相应的信息以便处理这些问题。在 axios 中，我们会通过使用 <code>catch</code> 来做这件事。</p>
<pre><code class="hljs js">axios
  .get(<span class="hljs-string">'https://api.coindesk.com/v1/bpi/currentprice.json'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> (<span class="hljs-keyword">this</span>.info = response.data.bpi))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error))</code></pre>
<p>这样我们就会知道在请求 API 的过程中是否有地方出错了，不过当数据长时间生成不出来或 API 不工作的时候会怎样呢？现在用户将会什么都看不到。我们可能想为这种情况构建一个加载效果，然后在根本无法获取数据时通知用户。</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  data () &#123;
    <span class="hljs-keyword">return</span> &#123;
      <span class="hljs-attr">info</span>: <span class="hljs-literal">null</span>,
      <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">errored</span>: <span class="hljs-literal">false</span>
    &#125;
  &#125;,
  <span class="hljs-attr">filters</span>: &#123;
    currencydecimal (value) &#123;
      <span class="hljs-keyword">return</span> value.toFixed(<span class="hljs-number">2</span>)
    &#125;
  &#125;,
  mounted () &#123;
    axios
      .get(<span class="hljs-string">'https://api.coindesk.com/v1/bpi/currentprice.json'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> &#123;
        <span class="hljs-keyword">this</span>.info = response.data.bpi
      &#125;)
      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> &#123;
        <span class="hljs-built_in">console</span>.log(error)
        <span class="hljs-keyword">this</span>.errored = <span class="hljs-literal">true</span>
      &#125;)
      .finally(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-keyword">this</span>.loading = <span class="hljs-literal">false</span>)
  &#125;
&#125;)</code></pre>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bitcoin Price Index<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">section</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"errored"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>We're sorry, we're not able to retrieve this information at the moment, please try back later<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">section</span> <span class="hljs-attr">v-else</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"loading"</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">v-else</span>
      <span class="hljs-attr">v-for</span>=<span class="hljs-string">"currency in info"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"currency"</span>
    &gt;</span>
      &#123;&#123; currency.description &#125;&#125;:
      <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"lighten"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">v-html</span>=<span class="hljs-string">"currency.symbol"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>&#123;&#123; currency.rate_float | currencydecimal &#125;&#125;
      <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>你可以在下面的例子中点击 Rerun 按钮以便看到我们从 API 获取数据时的加载状态：</p>
<p></p><p data-height="300" data-theme-id="32763" data-slug-hash="6c01922c9af3883890fd7393e8147ec4" data-default-tab="result" data-user="Vue" data-embed-version="2" data-pen-title="Fourth Step Axios and Vue" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Vue (<a href="https://codepen.io/Vue" target="_blank" rel="noopener">@Vue</a>)的 <a href="https://codepen.io/team/Vue/pen/6c01922c9af3883890fd7393e8147ec4/" target="_blank" rel="noopener">axios 和 Vue：第四步</a>。</p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<p>我们还可以做进一步优化，如用组件来实现不同部分、给出更明确的错误报告。这都取决于你使用的 API 以及应用的复杂度。</p>
<h2 id="替代方案"><a href="#%E6%9B%BF%E4%BB%A3%E6%96%B9%E6%A1%88" class="headerlink" title="替代方案"></a>替代方案</h2><h3 id="Fetch-API"><a href="#Fetch-API" class="headerlink" title="Fetch API"></a>Fetch API</h3><p><a href="https://developers.google.com/web/updates/2015/03/introduction-to-fetch" target="_blank" rel="noopener">Fetch API</a> 是一个用于此类请求的强大的原生 API。你可能听说过 Fetch API 其中的一个好处，就是你不需要在使用它的时候额外加载一个外部资源。确实如此！但是……目前它还没有被浏览器完全支持，所以你仍然需要一个 polyfill。使用这个 API 还有很多别的注意事项，这也是为什么大家现阶段还是更喜欢 axios 多一些。当然这个事情在未来可能会发生改变。</p>
<p>如果你对使用 Fetch API 有兴趣，这里有一些<a href="https://scotch.io/@bedakb/lets-build-type-ahead-component-with-vuejs-2-and-fetch-api" target="_blank" rel="noopener">非常棒的文章</a>来解释如何使用它。</p>
<h2 id="总结"><a href="#%E6%80%BB%E7%BB%93" class="headerlink" title="总结"></a>总结</h2><p>其实 Vue 和 axios 可以在一起配合的事情不只是访问和展示一个 API。你也可以和 Serverless Function 通信，向一个有写权限的 API 发送发布/编辑/删除请求等等。由于这两个库的集成很简单直接，它便成为了需要在工作流中集成 HTTP 客户端的开发者的常见选择。</p>

  
  
  <div class="footer">
      <script src="https://m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/cookbook/using-axios-to-consume-apis.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>

        
      </div>
      <script src="../../js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="../../js/css.escape.js"></script>
    <script src="../../js/common.js"></script>

    <!-- search -->
    <link href="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="../../css/search.css">
    <script src="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
